package service

import (
	"context"
	"encoding/json"
	"time"
	"user-service/basic/config"
	__ "user-service/basic/proto"
	"user-service/handler/model"
)

func (s *Server) PackageList(_ context.Context, in *__.PackageListReq) (*__.PackageListResp, error) {
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var packages []model.Package
	config.DB.Offset(int(offset)).Limit(int(pageSize)).Order("created_at desc").Find(&packages)
	var packagelist []*__.PackageList
	for _, m := range packages {
		list := __.PackageList{
			PackageName:    m.PackageName,
			HospitalId:     m.HospitalId,
			Price:          m.Price,
			OriginalPrice:  m.OriginalPrice,
			Items:          m.Items,
			ValidityPeriod: m.ValidityPeriod,
		}
		packagelist = append(packagelist, &list)
	}
	marshal, _ := json.Marshal(packagelist)
	config.Rdb.Set(config.Ctx, "packagelist", marshal, time.Hour*24)
	return &__.PackageListResp{
		List: packagelist,
	}, nil
}
